package bcnet.dao;

import java.util.ArrayList;
import java.util.List;

import bcnet.domain.CodeVO;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.CompositeFilterOperator;
import com.google.appengine.api.datastore.Query.Filter;
import com.google.appengine.api.datastore.Query.FilterOperator;
import com.google.appengine.api.datastore.Query.FilterPredicate;
import com.google.appengine.api.datastore.Query.SortDirection;
import com.google.appengine.api.datastore.QueryResultIterable;
import com.google.appengine.api.datastore.QueryResultIterator;

public class CodeDao {
	public void addCode(CodeVO codeVO){
		DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
		Entity code = new Entity("Code");
		code.setProperty("code", codeVO.getCode());
		datastore.put(code);
	}
	
	public List<CodeVO> getCodeList(int fromCode, int toCode){
		
		DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
		Filter filter1 = new FilterPredicate("code",FilterOperator.GREATER_THAN_OR_EQUAL,fromCode);
		Filter filter2 = new FilterPredicate("code",FilterOperator.LESS_THAN_OR_EQUAL,toCode);
		Filter codeFilter = CompositeFilterOperator.and(filter1, filter2);
		Query q = new Query("Code").setFilter(codeFilter).addSort("code",SortDirection.ASCENDING);
		//Query q = new Query("Code").addSort("code",SortDirection.ASCENDING);
		List<Entity> results = datastore.prepare(q).asList(FetchOptions.Builder.withChunkSize(500));
		List<CodeVO> list = new ArrayList<CodeVO>();
		CodeVO codeVO = null;
		for(int i=0; i<results.size(); i++){
			codeVO = new CodeVO();
			codeVO.setCode((Long)results.get(i).getProperty("code"));
			list.add(codeVO);
		}
		return list;
	}
	
	public void deleteCodeList(){
		DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
		List<Key> keys = new ArrayList<Key>();
		Query q = new Query("Code");
		PreparedQuery pq = datastore.prepare(q);
		QueryResultIterable<Entity> result = pq.asQueryResultIterable(FetchOptions.Builder.withChunkSize(500));

		QueryResultIterator<Entity> iterator = result.iterator();
		while (iterator.hasNext()) {
		  keys.add(iterator.next().getKey());
		}

		datastore.delete(keys);
	}
	

}
